package edu.jxufe.nb112.common.web.support.captcha;

/*******************************************************************************
 * (c) Copyright 2017 lvxi. All Rights Reserved.
 ******************************************************************************/
import edu.jxufe.nb112.common.code.mode.JsonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
public class JcaptchaImageSupport {
    private final static Logger LOG = LoggerFactory.getLogger(JcaptchaImageSupport.class.getName());

    @Autowired
    private JcaptchaService jcaptchaService;

    @RequestMapping(value = "/captcha.jpg",method = RequestMethod.GET)
    public void handleRequest(@RequestParam(value = "p", required = false, defaultValue = "") String id, HttpServletRequest request, HttpServletResponse response) {
        try {
            ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
            String captchaId = request.getSession().getId();
            BufferedImage challenge = jcaptchaService.getImageChallengeForID(id+":"+captchaId , request.getLocale());
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0L);
            response.setContentType("image/jpeg");

            ImageIO.write(challenge, "jpeg", jpegOutputStream);
            byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

            ServletOutputStream respOs = response.getOutputStream();
            respOs.write(captchaChallengeAsJpeg);
            respOs.flush();
            respOs.close();
        } catch (IOException e) {
            LOG.error("验证码生成错误: {}", e.getMessage());
        }
    }

    @RequestMapping(value = "/captcha-verify",method = RequestMethod.POST)
    public @ResponseBody JsonResponse validateRequest(@RequestParam(value = "p", required = false, defaultValue = "") String id, @RequestParam("verify") String verify, HttpServletRequest request) {
        String captchaId = id+":"+request.getSession().getId();
        Boolean isValidate = jcaptchaService.checkResponseForID(captchaId, verify);
        return  JsonResponse.create(isValidate);
    }

}
